﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class WebCamTool : SingletonMono<WebCamTool>
{

    string DeviceName;
    WebCamTexture webCamera;
    Texture2D tex2d;

    public void StartWebCamera(RawImage raw)
    {
        StartCoroutine(CoWebCamera(raw));
    }
    public void StopWebCamera()
    {
        if (webCamera != null)
            webCamera.Stop();
    }

    /// <summary>    
    /// 初始化摄像头  
    /// </summary>    
    IEnumerator CoWebCamera(RawImage raw)
    {
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            WebCamDevice[] devices = WebCamTexture.devices;
            if(devices.Length>0)
            {
                DeviceName = devices[0].name;
                webCamera = new WebCamTexture(DeviceName, Screen.width, Screen.height, 60);
                raw.texture = webCamera;
                webCamera.Play();
            }
        }
    }

    Texture2D TextureToTexture2D(Texture texture)
    {
        Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
        RenderTexture currentRT = RenderTexture.active;
        RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 32);
        Graphics.Blit(texture, renderTexture);

        RenderTexture.active = renderTexture;
        texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
        texture2D.Apply();

        RenderTexture.active = currentRT;
        RenderTexture.ReleaseTemporary(renderTexture);

        return texture2D;
    }

    public byte[] GetBytes(RawImage image)
    {
        Texture2D tex2d = TextureToTexture2D(image.texture);
        return tex2d.EncodeToJPG();
    }
}
